package com.sp.homework;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

/**
 * 1. 编写一个接收端A, 和一个发送端B, 使用UDP协议完成
 * 2. 接收端在8888端口等待接收数据receive
 * 3. 发送端向接收端发送数据 "你是谁"
 * 4. 接收端接收到发送端发送的问题后, 返回 "吴彦祖", 否则返回 "what?"
 * 5. 接收端和发送端程序退出
 */
public class Homework02ReceiverA {
    public static void main(String[] args) throws IOException {
        //创建一个DatagramSocket对象, 准备在8888端口接收数据
        DatagramSocket socket = new DatagramSocket(8888);

        //构建一个DatagramPacket对象, 准备接收数据
        byte[] buf = new byte[1024];
        DatagramPacket packet = new DatagramPacket(buf, buf.length);
        System.out.println("接收端准备接收问题");
        socket.receive(packet);
        String s = new String(packet.getData(), 0, packet.getLength());
        System.out.println(s);

        //对packet进行拆包, 取出数据并显示
        int length = packet.getLength();//实际接收到的数据字节长度
        byte[] data = packet.getData();//接收到数据
        String s1 = new String(data, 0, length);
        System.out.println(s1);
        String answer = "";
        if (s.equals("你是谁啊")) {
            answer = "吴彦祖";
        } else {
            answer = "what?";
        }

        data = answer.getBytes();
        packet = new DatagramPacket(data, data.length, InetAddress.getByName("192.168.0.101"), 9998);
        socket.send(packet);

        socket.close();
        System.out.println("接收端退出");
    }
}
